﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Security.AccessControl;

namespace BugSnapper
{
    public class Logger
    {
        private static void AddRule(string filePath, string account, FileSystemRights rights, AccessControlType controlType)
        {
            FileSecurity fSecurity = File.GetAccessControl(filePath);
            fSecurity.AddAccessRule(new FileSystemAccessRule(account, rights, controlType));
            File.SetAccessControl(filePath, fSecurity);
        }

        private static void SetRule(string filePath, string account, FileSystemRights rights, AccessControlType controlType)
        {
            FileSecurity fSecurity = File.GetAccessControl(filePath);
            fSecurity.ResetAccessRule(new FileSystemAccessRule(account, rights, controlType));
            File.SetAccessControl(filePath, fSecurity);
        }

        private string FileName
        {
            get
            {
                if (!Directory.Exists(Convert.ToString(System.Environment.CurrentDirectory) + "\\Logs\\"))
                {
                    Directory.CreateDirectory(Convert.ToString(System.Environment.CurrentDirectory) + "\\Logs\\");
                }
                string fileName = Convert.ToString(System.Environment.CurrentDirectory) + "\\Logs\\" + "ErrorLog" + DateTime.Today.Date.ToShortDateString().Replace("/", "") + ".Log";
                if (!File.Exists(fileName))
                {
                    File.Create(fileName);
                }
                return fileName;
            }
        }

        /// <summary>
        /// Takes a System.Exception object and logs the Error in the Application Directory.
        /// </summary>
        /// <param name="ex"></param>
        private void LogError(string ErrorMessage)
        {
            try
            {
                ErrorMessage = System.Environment.NewLine + System.Environment.NewLine + DateTime.Now.ToString() + System.Environment.NewLine + ErrorMessage;

                SetRule(FileName, "Everyone", FileSystemRights.Write, AccessControlType.Allow);

                File.AppendAllText(FileName, ErrorMessage);
            }
            catch
            {
            }
        }

        /// <summary>
        /// Takes System.String ErrorMessage as Parameter and Logs over the path Application\Logs\.
        /// </summary>
        /// <param name="ErrorMessage"></param>
        public void ProcessError(string ErrorMessage)
        {
            LogError(ErrorMessage);
        }

        /// <summary>
        /// Takes System.Exception ex as Parameter and Logs over the path Application\Logs\.
        /// </summary>
        /// <param name="ErrorMessage"></param>
        public void ProcessError(Exception ex)
        {
            LogError(ex.Message + System.Environment.NewLine + ex.StackTrace);
        }
    }
}
